package com.ceshiren.chnjx.wework.page;

import com.ceshiren.chnjx.wework.utils.GetCookiesUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;

/**
 * @author: JJJJ
 * @date:2021/11/2 16:55
 * @Description: TODO
 */
public class WeWork extends BasePage {


    private WebDriver driver;

    public void init(){
        System.setProperty("webdriver.chrome.driver", "F:\\chromedriver\\chromedriver_95\\chromedriver.exe");
        driver = new ChromeDriver();
        // 设置cookie
        setCookies();
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
        driver.manage().window().maximize();

    }

    public MainPage getMainPage(){
        init();
        return new MainPage(driver);
    }

    public void setCookies(){
        ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
        TypeReference<List<HashMap<String,Object>>> typeReference = new TypeReference<List<HashMap<String, Object>>>(){};
        // 判断cookies是否存在
        File file = new File("cookies.yaml");
        if (!file.exists()){
            try {
                GetCookiesUtil.getCookies(driver);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 设置cookies
        try {
            driver.get("https://work.weixin.qq.com/wework_admin/frame");
            List<HashMap<String, Object>> cookies = objectMapper.readValue(file, typeReference);
            cookies.forEach(cookie -> {
                driver.manage().addCookie(new Cookie(cookie.get("name").toString(),cookie.get("value").toString()));
            });
            driver.navigate().refresh();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
